/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.gateway.controller;

import lombok.AllArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Arisgo
 * @since 2024/6/2
 */
@RestController
@AllArgsConstructor
@RequestMapping(value = "/cloud")
public class InstanceController {
    
    private final DiscoveryClient discoveryClient;
    private final RedisTemplate<String, Object> redisTemplate;

    @GetMapping(value = "/instance")
    public Map<String, List<ServiceInstance>> instances() {
        Map<String, List<ServiceInstance>> instances = new HashMap<>(16);
        List<String> services = discoveryClient.getServices();
        services.forEach(s -> {
            List<ServiceInstance> list = discoveryClient.getInstances(s);
            instances.put(s, list);
        });
        Object instance = redisTemplate.opsForValue().get("instance");
        System.out.println("test redis: " + instance);
        return instances;
    }

    @DeleteMapping(value = "/redis/clear")
    public boolean clearRedis() {
        Set<String> keys = redisTemplate.keys("*");
        if (CollectionUtils.isEmpty(keys)) {
            return true;
        }
        redisTemplate.delete(keys);
        return true;
    }

    @DeleteMapping(value = "/redis/{key}")
    public Boolean delRedis(@PathVariable(name = "key") String key) {
        return redisTemplate.delete(key);
    }

    @GetMapping(value = "/redis")
    public Set<String> findKeys() {
        return redisTemplate.keys("*");
    }

    @GetMapping(value = "/redis/{key}")
    public Object findRedis(@PathVariable(name = "key") String key) {
        return redisTemplate.opsForValue().get(key);
    }
    
}
